package com.xcjh.opencv.util;


import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.lang.func.Func0;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 缓存工具类
 * @author yangyi
 */
@Slf4j
public class CacheUtils {

    /**
     * 总体的缓存对象，不同类型不同缓存
     */
    public static final Map<String,TimedCache<String,Object>> TIMED_CACHE=new HashMap<>();

    public static TimedCache<String,Object> getTimeCache(CacheType type){
        //获取总map总是否存在该map，如果不存在的类型就新建一个cache
        return TIMED_CACHE.computeIfAbsent(type.getCode(), k -> CacheUtil.newTimedCache(type.getTimeOut()));
    }


    /**
     * 获取缓存，不存在就执行查询方法
     * @param key 缓存的key 一般情况下是Long id,也可以是 List String.
     * @param type 业务缓存类型
     * @param exeFunction 不存在的时候，需要执行的代码
     * @return 返回值
     */
    public static <T> T getOrExeCache(String key, CacheType type, Func0<T> exeFunction){
        return (T) getTimeCache(type).get(key, false, (Func0<Object>) exeFunction);
    }

    public static void main(String[] args) throws Exception {
//        Object data = getOrExeCache("1", CacheType.ADMIN_SYS_USER, () -> {
//            System.out.println("查询数据库");
//            return 222;
//        });
    }


    /**
     * 用户缓存类型
     */
    public enum CacheType {
        /**
         * 图片信息
         */
        PIC("pic","图片",60000*1000),
        ;

        private String code;
        private String message;
        private Integer timeOut;

        private CacheType(String code, String message,Integer timeOut) {
            this.code = code;
            this.message = message;
            this.timeOut=timeOut;
        }

        public String getCode() {
            return code;
        }

        public Integer getTimeOut() {
            return timeOut;
        }

        public void setTimeOut(Integer timeOut) {
            this.timeOut = timeOut;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public static CacheType match(String key) {

            CacheType result = null;

            for (CacheType s : values()) {
                if (Objects.equals(s.getCode(), key)) {
                    result = s;
                    break;
                }
            }

            return result;
        }

        public static CacheType catchMessage(String msg) {

            CacheType result = null;

            for (CacheType s : values()) {
                if (s.getMessage().equals(msg)) {
                    result = s;
                    break;
                }
            }

            return result;
        }
    }
}
